package shape

import (
	"database/sql/driver"
	"encoding/json"
	"fmt"
	"gitee.com/git_public/vfaith/sugar"
	"gitee.com/git_public/vfaith/sugar/regexpv"
	"strings"
	"time"
)

type UnixTime struct {
	*time.Time
}

func NewUnixNow() *UnixTime {
	now := time.Now()
	return &UnixTime{Time: &now}
}

func NewUnixTime(str string) *UnixTime {
	if str == "" {
		return &UnixTime{Time: nil}
	}
	if regexpv.DateRegExp(str) {
		str = str + " 00:00:00"
	}
	parsedTime, err := sugar.StringToTime(str) // 根据需要定义时间格式
	if err != nil {
		return nil
	}
	return &UnixTime{Time: parsedTime}
}

func (ut *UnixTime) MarshalJSON() ([]byte, error) {
	//time.ParseInLocation(ut.Time, str, time.Local)
	timeStr := sugar.FormatTimeToDateTime(*ut.Time)
	return json.Marshal(timeStr)
}

// UnmarshalJSON 方法实现，来解析自定义格式的时间
func (ut *UnixTime) UnmarshalJSON(b []byte) (err error) {
	str := strings.Trim(string(b), `"`)
	if len(str) == 0 {
		return nil
	}

	*ut.Time, err = time.ParseInLocation(time.DateTime, str, time.Local)
	return err
}

// Scan 实现 sql.Scanner 接口
func (ut *UnixTime) Scan(value interface{}) error {
	if v, ok := value.(int64); ok {
		location, _ := time.LoadLocation("Asia/Shanghai")
		t := time.Unix(v, 0).In(location)
		*ut = UnixTime{Time: &t}
		return nil
	}
	return fmt.Errorf("unsupported scan type %T, expected time.Time", value)
}

// Value 实现 driver.Valuer 接口
func (ut *UnixTime) Value() (driver.Value, error) {
	if ut == nil || ut.Time == nil {
		return nil, nil
	}
	return (*ut.Time).Unix(), nil
}
